package org.csu.jpetstoreagain.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.csu.jpetstoreagain.domain.Cart;
import org.csu.jpetstoreagain.persistence.CartMapper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartService extends ServiceImpl<CartMapper, Cart> {
    public void addItemToCart(String userid, String itemid) {
        Cart cart = containsItem(userid, itemid);
        if(cart != null)
        {
            cart.setQuantity(cart.getQuantity()+1);
            updateById(cart);
        } else{
            cart = new Cart();
            cart.setQuantity(1);
            cart.setItemId(itemid);
            cart.setUserid(userid);
            save(cart);
        }
    }

    public void updateCart(Cart cart) {
        updateById(cart);
    }

    public void removeItem(String userid, String itemid) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserid, userid);
        wrapper.eq(Cart::getItemId, itemid);
        remove(wrapper);
    }

    public void clearCart(String userid) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserid, userid);
        remove(wrapper);
    }
    public List<Cart> listByUserId(String userid) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserid, userid);
        return list(wrapper);
    }
    public Cart containsItem(String userid, String itemid) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserid, userid);
        wrapper.eq(Cart::getItemId, itemid);
        return getOne(wrapper);
    }

}
